package com.penglecode.dp.structural.proxy;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibProxy implements MethodInterceptor {

	private static final Log logger = LogFactory.getLog(ProxyUserService.class);
	
	private Enhancer enhancer = new Enhancer();
	
	@SuppressWarnings("unchecked")
	public <T> T getProxy(Class<?> targetClass){
		if(targetClass == null){
			throw new IllegalArgumentException("'targetClass' parameter can not be null!");
		}
		if(targetClass.isInterface()){
			throw new IllegalArgumentException("'targetClass' parameter can not be a interface!");
		}
		enhancer.setSuperclass(targetClass);
		enhancer.setCallback(this);
		return (T) enhancer.create();
	}

	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if(args != null && args.length > 0){
			for(Object param : args){
				logger.debug(">>> param[" + (param == null ? Object.class : param.getClass()) + "] : " + param);
			}
		}
		Object result = proxy.invokeSuper(obj, args);
		logger.debug(">>> result[boolean] : " + result);
		return result;
	}

}
